let dumpPage = (page, params, type) => {
	if (!page.startsWith('/')) {
		page = '/' + page;
	}
	let routeInfo = {
		url: page,
		type: type || 'to'
	}
	if (!isEmpty(params)) {
		routeInfo.params = params
	}
	uni.$uv.route(routeInfo)
};
let copyIt = function(str) {
	return new Promise(function(resolve, reject) {
		//#ifdef H5
		const textarea = document.createElement('textarea');
		textarea.value = str;
		textarea.readOnly = true;
		document.body.appendChild(textarea);
		textarea.select();
		textarea.setSelectionRange(0, str.length);
		document.execCommand('copy');
		textarea.remove();
		resolve(true);
		//#endif
		// #ifndef H5
		uni.setClipboardData({
			data: str,
			success: function() {
				uni.hideToast();
				resolve(true);
			},
			fail: function() {
				reject(false);
			}
		});
		// #endif
	});
};
let addFavorites = (dataKey, item) => {
	let cache_key = "_favorites";
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: cache_key,
			success: (res) => {
				// console.log(res.data);
				let odata = res.data || {};
				let result = true
				if (!getProperty(odata, dataKey)) {
					odata[dataKey] = item
				} else {
					delete odata[dataKey];
					result = false
				}
				uni.setStorage({
					key: cache_key,
					data: odata
				});
				resolve(result);
			},
			fail: (e) => {
				// 第 一次不存在数据会异常
				let data = {}
				data[dataKey] = item
				uni.setStorage({
					key: cache_key,
					data: data
				});
				resolve(true);
			}
		});
	});
};
let addHistorys = (dataKey, item) => {
	let cache_key = "_historys";
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: cache_key,
			success: (res) => {
				// console.log(res.data);
				let odata = res.data || {};
				let result = true
				if (!getProperty(odata, dataKey)) {
					odata[dataKey] = item
				} else {
					delete odata[dataKey];
					result = false
				}
				uni.setStorage({
					key: cache_key,
					data: odata
				});
				resolve(result);
			},
			fail: (e) => {
				// 第 一次不存在数据会异常
				let data = {}
				data[dataKey] = item
				uni.setStorage({
					key: cache_key,
					data: data
				});
				resolve(true);
			}
		});
	});
};
let selfHost = () => {
	//解析出自己的host
	let href = self.location.href;
	if (href.indexOf('pages') != -1) {
		href = href.split('pages')[0];
	}
	if (href.indexOf('#') != -1) {
		href = href.split('#')[0];
	}
	return href;
};
//使用rich-text组件时的html有些tag要过滤
let filterRichTextHtml = (html) => {
	return html.replace(/<img/gi, '<img loading="lazy" ignore style="width:100%;height:auto;"').replace(
			/<section/ig, '<div')
		.replace(/\/section>/ig, '\/div>').replace(/<map.+?>.+?<\/map>/ig, '').replace(
			/<code.+?>.+?<\/code>/ig, '')
		.replace(/<embed/ig, '<video autopause="true" controls="true" show-mute-btn="true"').replace(
			/<\/embed>/ig, '</video>');
};
//随机字符
let randomString = (len, chars) => {
	chars = chars || '0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	len = len || 6;
	let maxPos = chars.length;
	let s = '';
	for (let i = 0; i < len; i++) {
		s += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return s;
};
//截取字符串
let cutString = function(str, startString, endString) {
	let si = str.indexOf(startString);
	if (si !== -1) {
		str = str.substring(si + startString.length);
	}
	if (endString) {
		si = str.indexOf(endString);
		if (si !== -1) {
			str = str.substring(0, si);
		}
	}
	return str;
};
//对应php的htmlspecialchars的字符还原
let htmlSpecialCharsDecode = function(str) {
	if (uni.$uv.test.isEmpty(str)) {
		return null;
	}
	str = str.replace(/&amp;/g, '&');
	str = str.replace(/&lt;/g, '<');
	str = str.replace(/&gt;/g, '>');
	str = str.replace(/&quot;/g, "\"");
	str = str.replace(/&#039;/g, "'");
	return str;
};
//判断字符是否为空的方法
let isEmpty = (obj) => {
	if (typeof obj == "undefined" || obj == 'null' || obj == null || obj === "" || obj === NaN) {
		return true;
	} else if (Object.prototype.toString.call(obj) == "[object String]") {
		if (obj === "") {
			return true;
		} else {
			return false;
		}
	} else if (Object.prototype.toString.call(obj) == "[object Array]") {
		if (obj.length <= 0) {
			return true;
		} else {
			return false;
		}
	} else if (Object.prototype.toString.call(obj) == "[object Object]") {
		if (Object.keys(obj).length <= 0) {
			return true;
		}
		return false;
	} else {
		return false;
	}
};
//一个扫码参数的还原
let scene2obj = async (scene) => {
	if (typeof scene != 'string') {
		return {};
	}
	scene = decodeURIComponent(scene);
	//第一个字符判断是哪个页面的参数
	let fi = scene.substring(0, 1);
	let data = scene.substring(1).split('_');
	//obj的取值与后台的scene的定义相关
	let obj = {};
	switch (fi) {
		case 'a':
			obj.spid = data[0] || 0;
			break;
		default:
			// 只有推广账号的识别
			obj.spid = data[0] || 0;
			break;
	}
	return obj;
};
let getProperty = (obj, key) => {
	return uni.$uv.getProperty(obj, key)
};
//推广者
let getSpid = function() {
	let spid = uni.getStorageSync('spid');
	let regPos = /^[0-9]\d+$/; //判断是否是数字。
	if (null == spid || !regPos.test(spid)) {
		spid = 0;
	}
	return spid;
};
let saveSpid = function(spid) {
	if (typeof spid == 'undefined' || spid == null) {
		spid = 0;
	}
	let regPos = /^[0-9]\d+$/; //判断是否是数字。
	if (!regPos.test(spid)) {
		spid = 0;
	}
	//已经有推广id时就不重新保存了
	uni.getStorage({
		key: 'spid',
		success: function(res) {
			if (typeof res.data == 'undefined' || res.data == null) {
				uni.setStorage({
					key: 'spid',
					data: spid
				});
			}
		},
		fail: function() {
			uni.setStorage({
				key: 'spid',
				data: spid
			});
		}
	});
};
let nowPlatform = function() {
	let state = {
		//#ifdef APP-PLUS
		platform: 2, //指定平台类型为App
		//#endif
		//#ifdef MP-WEIXIN
		platform: 1, //指定平台类型为微信小程序
		//#endif
		//#ifdef H5
		platform: 3, //指定平台类型为H5,4为pc
		//#endif
		//#ifdef MP-ALIPAY
		platform: 5, //指定平台类型为支付宝小程序
		//#endif
		//#ifdef MP-BAIDU
		platform: 6, //指定平台类型为百度小程序
		//#endif
		//#ifdef MP-TOUTIAO
		platform: 7, //指定平台类型为头条小程序
		//#endif
		//#ifdef MP-QQ
		platform: 8, //指定平台类型为QQ小程序
		//#endif
	};
	//#ifdef H5
	if (isPc()) {
		state.platform = 4;
	}
	//#endif
	return state.platform;
};
let isPc = function() {
	let r = false;
	//#ifdef H5
	if (!navigator.userAgent.match(
			/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
		)) {
		r = true; // PC端
	}
	//#endif
	return r;
};
let isWeiXin = function() {
	let r = false;
	//#ifdef H5
	var ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		r = true;
	}
	//#endif
	return r;
};
// 当前页路径及参数,主要用来跳转登陆时返回当前页
let nowPage = () => {
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[routes.length - 1].route //获取当前页面路由
	let curParam = routes[routes.length - 1].options; //获取路由参数
	if (!curRoute.startsWith('/')) {
		curRoute = '/' + curRoute;
	}
	return curRoute + uni.$uv.queryParams(curParam); //'?' + qs.stringify(curParam);
};
// 重新登陆
let reLogin = () => {
	uni.setStorage({
		key: '_login_back_page',
		data: nowPage(),
		success: () => {
			// uni.showModal({
			// 	title: '提示',
			// 	content: '请重新登录',
			// 	showCancel: false,
			// 	success: (res) => {
			// 		if (res.confirm) {
			// 			uni.navigateTo({
			// 				url: '/pages/login/login'
			// 			});
			// 		}
			// 	}
			// });
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
	});
};
// 用来获取上一页面,把当前页面数据传回上一页
let prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
};
let marginRight2px = (cssClass) => {
	return margin2px(cssClass, 'right');
};
let marginLeft2px = (cssClass) => {
	return margin2px(cssClass, 'left');
};
let marginLR2px = (cssClass) => {
	return margin2px(cssClass, 'lr');
};
// 计算margin样式的实际像素
let margin2px = (cssClass, flag) => {
	if (isEmpty(cssClass)) {
		return 0;
	}
	if (['top', 'bottom', 'tb', 'lr', 'left', 'right'].indexOf(flag) == -1) {
		return 0;
	}
	let rpx = 0;
	let types = {
		'xs': 10,
		'sm': 20,
		'df': 30,
		'lg': 40,
		'xl': 50
	};
	Object.keys(types).forEach((key) => {
		let value = types[key];
		let findClass = `css-margin-${flag}-${key}`;
		if (cssClass.indexOf(findClass) != -1) {
			//与uni.scss里定义的样式值一致
			rpx = value;
		}
	});
	if (rpx == 0) {
		let dfClass1 = `css-margin-${flag}`;
		let dfClass2 = ` css-margin-${flag} `;
		if (cssClass.indexOf(dfClass2) != -1 || cssClass.startsWith(dfClass1)) {
			rpx = types['df'];
		}
	}
	return uni.upx2px(rpx);
};
//内容显示去除左右margin的屏幕宽
let boxWidth = (marginClass, screenWidth) => {
	if (!screenWidth) {
		screenWidth = uni.screenWidth;
	}
	// 空样式
	if (isEmpty(marginClass)) {
		return screenWidth;
	}
	let rpx = marginLR2px(marginClass);
	return screenWidth - rpx * 2;
};
export default {
	dumpPage,
	copyIt,
	addFavorites,
	addHistorys,
	filterRichTextHtml,
	randomString,
	cutString,
	htmlSpecialCharsDecode,
	isEmpty,
	getProperty,
	scene2obj,
	getSpid,
	selfHost,
	saveSpid,
	nowPlatform,
	isPc,
	isWeiXin,
	nowPage,
	reLogin,
	prePage,
	margin2px,
	marginLR2px,
	marginLeft2px,
	marginRight2px,
	boxWidth
}